"""
Verify AIPPT API - Test template listing and PPT generation

Main APIs to test:
1. Template APIs:
   - GET  /api/ppt/template/options - Get template filter options
   - POST /api/ppt/templates - List templates with pagination
   - POST /api/ppt/randomTemplates - Get random templates

2. PPT Generation APIs (V2 - Recommended):
   - POST /api/ppt/v2/createTask - Create a PPT generation task
   - GET  /api/ppt/v2/options - Get generation options
   - POST /api/ppt/v2/generateContent - Generate outline and content
   - POST /api/ppt/v2/generatePptx - Generate PPT file
"""
import os
import sys
import requests
import json
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configuration
AIPPT_TOKEN = os.getenv("AIPPT_TOKEN")
AIPPT_BASE_URL = os.getenv("AIPPT_BASE_URL", "https://docmee.cn/api")

# Verify configuration
if not AIPPT_TOKEN:
    print("ERROR: AIPPT_TOKEN not found in environment variables")
    sys.exit(1)

print(f"AIPPT Base URL: {AIPPT_BASE_URL}")
print(f"AIPPT Token: {AIPPT_TOKEN[:10]}..." if AIPPT_TOKEN else "AIPPT Token: Not set")
print("-" * 60)


def make_request(method, endpoint, **kwargs):
    """
    Make HTTP request to AIPPT API

    Args:
        method: HTTP method (GET, POST, etc.)
        endpoint: API endpoint (e.g., '/ppt/templates')
        **kwargs: Additional arguments for requests
    """
    url = f"{AIPPT_BASE_URL}{endpoint}"

    # Add token to headers
    headers = kwargs.get('headers', {})
    headers['token'] = AIPPT_TOKEN
    kwargs['headers'] = headers

    print(f"\n{method} {url}")
    if 'json' in kwargs:
        print(f"Request body: {json.dumps(kwargs['json'], indent=2, ensure_ascii=False)}")

    try:
        response = requests.request(method, url, **kwargs)
        print(f"Status: {response.status_code}")

        if response.status_code == 200:
            try:
                data = response.json()
                print(f"Response: {json.dumps(data, indent=2, ensure_ascii=False)[:500]}")
                return data
            except json.JSONDecodeError:
                print(f"Response (text): {response.text[:500]}")
                return response.text
        else:
            print(f"Error: {response.text}")
            return None
    except Exception as e:
        print(f"Exception: {str(e)}")
        return None


# ============================================================
# Test 1: Get Template Options
# ============================================================
def test_template_options():
    """Test getting template filter options"""
    print("\n" + "=" * 60)
    print("TEST 1: Get Template Filter Options")
    print("=" * 60)

    result = make_request('GET', '/ppt/template/options')
    return result


# ============================================================
# Test 2: List Templates
# ============================================================
def test_list_templates():
    """Test listing templates with pagination"""
    print("\n" + "=" * 60)
    print("TEST 2: List Templates")
    print("=" * 60)

    payload = {
        "current": 1,
        "size": 5
    }

    result = make_request('POST', '/ppt/templates', json=payload)
    return result


# ============================================================
# Test 3: Get Random Templates
# ============================================================
def test_random_templates():
    """Test getting random templates"""
    print("\n" + "=" * 60)
    print("TEST 3: Get Random Templates")
    print("=" * 60)

    payload = {
        "count": 3
    }

    result = make_request('POST', '/ppt/randomTemplates', json=payload)
    return result


# ============================================================
# Test 4: Create PPT Task (V2)
# ============================================================
def test_create_task():
    """Test creating a PPT generation task"""
    print("\n" + "=" * 60)
    print("TEST 4: Create PPT Generation Task (V2)")
    print("=" * 60)

    # Use multipart/form-data
    files = {
        'type': (None, '1'),  # Type 1: Smart generation (theme/requirements)
        'content': (None, 'AI and Machine Learning in Modern Education')
    }

    url = f"{AIPPT_BASE_URL}/ppt/v2/createTask"
    headers = {'token': AIPPT_TOKEN}

    print(f"\nPOST {url}")
    print(f"Form data: type=1, content='AI and Machine Learning in Modern Education'")

    try:
        response = requests.post(url, files=files, headers=headers)
        print(f"Status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print(f"Response: {json.dumps(data, indent=2, ensure_ascii=False)}")
            return data
        else:
            print(f"Error: {response.text}")
            return None
    except Exception as e:
        print(f"Exception: {str(e)}")
        return None


# ============================================================
# Test 5: Get Generation Options (V2)
# ============================================================
def test_generation_options():
    """Test getting generation options for V2 API"""
    print("\n" + "=" * 60)
    print("TEST 5: Get Generation Options (V2)")
    print("=" * 60)

    result = make_request('GET', '/ppt/v2/options')
    return result


# ============================================================
# Test 6: Generate Content (V2) - Simple Test
# ============================================================
def test_generate_content(task_id=None):
    """Test generating outline and content"""
    print("\n" + "=" * 60)
    print("TEST 6: Generate Content (V2)")
    print("=" * 60)

    if not task_id:
        print("WARNING: No task_id provided, skipping this test")
        return None

    payload = {
        "taskId": task_id,
        "isStream": False  # Non-streaming for easier testing
    }

    result = make_request('POST', '/ppt/v2/generateContent', json=payload)
    return result


# ============================================================
# Main Execution
# ============================================================
if __name__ == "__main__":
    print("\n" + "=" * 60)
    print("AIPPT API Verification Script")
    print("=" * 60)

    # Test template-related APIs
    print("\n\n" + "#" * 60)
    print("# PART 1: Template APIs")
    print("#" * 60)

    template_options = test_template_options()
    templates_list = test_list_templates()
    random_templates = test_random_templates()

    # Test PPT generation APIs
    print("\n\n" + "#" * 60)
    print("# PART 2: PPT Generation APIs (V2)")
    print("#" * 60)

    generation_options = test_generation_options()
    task_result = test_create_task()

    # If task creation succeeded, try to generate content
    if task_result and 'data' in task_result:
        # Try both 'taskId' and 'id' as field names
        task_id = task_result['data'].get('taskId') or task_result['data'].get('id')
        if task_id:
            print(f"\nTask created successfully with ID: {task_id}")
            print("NOTE: Content generation test is commented out to avoid consuming credits")
            print("      Uncomment test_generate_content() in the code to test it")
            # Note: Generating content might take time and consume credits
            # Uncomment the following line to test content generation
            # content_result = test_generate_content(task_id)
        else:
            print("\nWARNING: Task creation response missing taskId/id field")

    # Summary
    print("\n\n" + "=" * 60)
    print("VERIFICATION SUMMARY")
    print("=" * 60)
    print(f"Template Options:       {'OK' if template_options else 'FAILED'}")
    print(f"List Templates:         {'OK' if templates_list else 'FAILED'}")
    print(f"Random Templates:       {'OK' if random_templates else 'FAILED'}")
    print(f"Generation Options:     {'OK' if generation_options else 'FAILED'}")
    print(f"Create Task:            {'OK' if task_result else 'FAILED'}")
    print("=" * 60)
